import React, { useCallback } from "react";
import { List, Pagination, message } from "antd";
import useJokes from "@/hooks/useJokes";
import style from "./jokes.module.css";

const Jokes = () => {
  const [page, setPage, responseData = {}, maxResult, setMaxResult] = useJokes(
    1,
    1
  );
  const onChange = useCallback(
    (page, pageSize) => {
      setPage(page);
      setMaxResult(pageSize);
    },
    [setMaxResult, setPage]
  );
  const copyText = useCallback(async (e) => {
    const inputArea = document.createElement("input");
    inputArea.style.opacity = "0";
    inputArea.value = e.target.innerText;
    document.body.appendChild(inputArea);
    inputArea.select(); // 选中文本
    try {
      await document.execCommand("Copy");
      message.success("复制成功");
    } catch {
      message.error("复制失败");
    }
    document.body.removeChild(inputArea);
  }, []);
  const textFormat = useCallback((item) => {
    let text = "";
    if (item || item.text) {
      text = item.text
        .replace(/([\d]+)、/gi, "<br>$1.")
        .replace(/^\s*<br>/, "");
    }
    return text;
  }, []);
  return (
    <React.Fragment>
      <List
        header={
          <div style={{ textAlign: "center" }}>
            -----------------------------A joke a
            day-----------------------------
          </div>
        }
        footer={
          <div style={{ textAlign: "center" }}>
            ---------------------------The doctor
            away---------------------------
          </div>
        }
        bordered
        dataSource={responseData.contentlist}
        renderItem={(item) => (
          <List.Item>
            <div
              className={style.text}
              onClick={copyText}
              dangerouslySetInnerHTML={{
                __html: textFormat(item),
              }}
            />
          </List.Item>
        )}
      />
      <Pagination
        className={style.right}
        onChange={onChange}
        total={responseData.allNum || 0}
        defaultPageSize={maxResult}
        current={page}
        hideOnSinglePage={true}
        disabled={responseData.allPages === 1}
      />
    </React.Fragment>
  );
};

export default Jokes;
